package com.leyou.user.controller;

import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

/**
 * User: ycs
 * Date: 2020/8/29
 * Time: 11:10
 *
 * @author: ycs
 * Description: No Description
 * 用户注册登录控制器
 */
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    /**
     * 判断用户名获取手机号唯一
     * @param data
     * @param type
     * @return
     */
    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean> IfPhoneOrUserName(@PathVariable("data")String data
                                    ,@PathVariable("type")String type){

        return ResponseEntity.ok(userService.IfPhoneOrUserName(data,type));
    }

    /**
     * 发送短信
     * @param phone
     * @return
     */
    @PostMapping("/code")
    public ResponseEntity<Void>sendCode(String phone){
        userService.sendCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 用户注册
     * @param user
     * @param code
     */
    @PostMapping("/register")
    public ResponseEntity<Void> userRegister(@Valid User user,
                                             BindingResult bindResult,
                                             @RequestParam("code") String code){
        //有异常信息
       if (bindResult.hasErrors()){
           //获取异常信息集合
           String error = bindResult.getFieldErrors()
                   .stream()
                   .map(FieldError::getDefaultMessage)
                   .collect(Collectors.joining("|"));
          throw  new LyException(error,501);
       }
        userService.userRegister(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 根据用户名与密码查询用户
     * @param username
     * @param password
     * @return
     */
    @GetMapping("/query")
    public ResponseEntity<User>findByUsernameAndPassword(
                                                        @RequestParam("username") String username,
                                                        @RequestParam("password")String password
                                                        ){
        User user=userService.findByUsernameAndPassword(username,password);
        return ResponseEntity.ok(user);
    }

}
